import type { ResumeData } from '../types';

function fillInput(element: HTMLInputElement | HTMLTextAreaElement | null, value: string) {
  if (!element) return;
  element.value = value;
  element.dispatchEvent(new Event('input', { bubbles: true }));
  element.dispatchEvent(new Event('change', { bubbles: true }));
}

export const beisenAdapter = {
  matcher: (url: URL) => 
    url.hostname.includes('beisen.com') || 
    url.hostname.includes('hotjob.cn') ||
    url.hostname.includes('lixiang.com'),

  filler: (resumeData: ResumeData) => {
    console.log('[AutoApply] 已激活 北森招聘(Beisen) 系统级适配器 V2');
    
    // 【核心升级】: 使用规则数组，让每个字段可以匹配多个关键词
    const fieldRules = [
      { key: 'basicInfo.name', keywords: ['姓名'] },
      { key: 'basicInfo.phone', keywords: ['手机号码', '手机号', '联系电话'] },
      { key: 'basicInfo.email', keywords: ['电子邮箱', '邮箱'] },
      { key: 'education.school', keywords: ['毕业院校', '学校名称'] },
      { key: 'education.major', keywords: ['专业'] },
    ];

    document.querySelectorAll('div.applyform-cell-label').forEach(labelDiv => {
      const labelElement = labelDiv as HTMLElement;
      const labelText = labelElement.textContent?.replace('*', '').trim() || '';

      // 遍历我们的新规则库
      for (const rule of fieldRules) {
        // 检查标签文本是否包含了任意一个关键词
        if (rule.keywords.includes(labelText)) {
          const [section, field] = rule.key.split('.');
          const value = (resumeData as any)[section]?.[field];

          if (value) {
            const formCell = labelElement.closest('.applyform-cell');
            if (formCell) {
              const inputBox = formCell.querySelector('input, textarea');
              if (inputBox) {
                console.log(`[AutoApply] 匹配规则 "${rule.key}" -> 找到标签 "${labelText}", 准备填写:`, value);
                if (inputBox instanceof HTMLInputElement || inputBox instanceof HTMLTextAreaElement) {
                  fillInput(inputBox, value);
                }
                break; // 匹配成功，跳出内层循环，处理下一个label
              }
            }
          }
        }
      }
    });

    alert('北森系统适配器V2填写完成！请检查。');
  },
};